package com.weizhizs.assistant.code.helper;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileHelper {

    public static void saveToFile(String packageOutPath,
                                  String content,
                                  String fileName) {
        try {
            // 固定输出到 d:\temp\generate-code 下
            String outputPath = "d:/temp/generate-code/"
                    + packageOutPath.replace(".", "/") + "/" + fileName;

            forceMakeDirs(outputPath);

            FileWriter fw = new FileWriter(outputPath);
            try (PrintWriter pw = new PrintWriter(fw)) {
                pw.println(content);
                pw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void forceMakeDirs(String fileName) {
        File file = new File(fileName);
        File parentFile = file.getParentFile();

        if (!parentFile.exists()) {
            boolean result = parentFile.mkdirs();
            if (!result) {
                System.out.println("路径创建失败: " + fileName);
            }
        }
    }

}
